package com.servlet.ihm;

import java.io.IOException;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.TreeSet;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.listener.ContextListener;
import com.servlet.form.Format;
import com.servlet.model.algorithmes.AccountComparator;
import com.servlet.model.base.Contact;
import com.servlet.model.base.Profile;
import com.servlet.model.database.BaseAcces;

public class ContactsServlet extends HttpServlet
{
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		

		HttpSession session = request.getSession();
		
		String email = (String)session.getAttribute("email");

		Profile profile = ContextListener.base.findProfile(email);
		
		request.setAttribute("profile", profile );
		
		BaseAcces base = ContextListener.base;

		ArrayList<Contact> contacts = base.findContacts(email);

		String[] ares = new String[contacts.size()];
		
		for( int i = 0 ; i < ares.length ; i++ )
		{
			if( contacts.get(i).getEmail_user1().compareTo(email) == 0 )
				ares[i] = contacts.get(i).getEmail_user2();
			else
				ares[i] = contacts.get(i).getEmail_user1();
		}
		
		Arrays.sort(ares);

		ArrayList<Profile> resultatsFinaux = new ArrayList<Profile>();
		
		for( int i = 0 ; i < ares.length ; i++ )
		{
			Profile p = base.findProfile(ares[i]);

			p.setMode( 0 );
			
			for( int j = 0 ; j < contacts.size() ; j++ )
			{
				if( p.getEmail().compareTo( contacts.get(j).getEmail_user1() ) == 0 || p.getEmail().compareTo( contacts.get(j).getEmail_user2() ) == 0 )
				{
					System.out.println(contacts.get(j).getIs_accepted());
					if(  !contacts.get(j).getIs_accepted() )
					{
						p.setMode( 1 );
					}
					else
					{
						p.setMode( 2 );
					}
				}
			}
			
			resultatsFinaux.add(p);
		}
		
		//System.out.println("Res : " + resultatsFinaux);
		session.setAttribute("contacts",  resultatsFinaux );
		session.setAttribute("contactsAppuie",  resultatsFinaux );

		//quelle rubrique est actuellement en surbrillance
		request.setAttribute("page", new String("contacts"));
		//rubrique dans la page
		request.setAttribute("rubrique", new String("Main"));
		RequestDispatcher dispatch = request.getRequestDispatcher("jsp/pageBase.jsp");
		dispatch.forward(request, response);
	}
}
